#include <iostream>
#include <unistd.h>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>

#define N 2
#define NUM 1024
using namespace std;

// child
void Write(int wfd)
{
    string s = "hello,I am child";
    pid_t self = getpid();
    int number = 0;

    char buffer[NUM];
    //int cnt=5;
    while (true)
    {
        sleep(1);

        buffer[0] = 0;
        snprintf(buffer, sizeof(buffer), "%s-%d-%d", s.c_str(), self, number);
        // cout<<buffer<<endl;
        ssize_t ret=write(wfd, buffer, strlen(buffer));
        number++;
        cout << number <<"  "<< ret<<endl;
        //cnt--;
    }
    //close(wfd);
}
// father  pipefd[0]
void Read(int rfd)
{
    char buffer[NUM] = {0};
    int cnt=5;
    while (cnt)
    {
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "father get amessage[" << getpid() << "]#" << buffer << endl;
        }
        else if (n == 0)
        {
            printf("father read file done\n");
            break;
        }
        cnt--;
    }
    close(rfd);
}
int main()
{
    int pipefd[N] = {0};
    int n = pipe(pipefd);
    if (n < 0)
    {
        return 0;
    }
    // cout<<"pipefd[0]"<<pipefd[0]<<"pipefd[1]"<<pipefd[1]<<endl;
    //  child w father r
    pid_t id = fork();
    if (id < 0)
        return 2;
    if (id == 0)
    {
        // child
        close(pipefd[0]);
        // IPC code
        Write(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }
    // father
    close(pipefd[1]);
    // IPC code
    Read(pipefd[0]);
    close(pipefd[0]);
    cout << "father close read fd:" << pipefd[0] << endl;
    sleep(5);
    int status = 0;
    pid_t rid = waitpid(id, &status, 0) ;
    if(rid<0) return 3;
    cout<<"wait child success:"<<rid<<"exit code:"<<((status>>8)&0xFF)<<"exit signl:"<<((status&0x7F))<<endl;
    sleep(5);
    return 0;
}
